import 'dart:convert';
import 'dart:core';

import 'package:dio/dio.dart';
import 'package:ecy_app_flutter/ecycommon/EcyCommonWidgets.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyEncrptyUtil.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import '../../constant/EcyEventConsnt.dart';
import '../../constant/color_constant.dart';
import '../../EcyRouter.dart';
import 'package:ecy_app_flutter/ecycommon/EcyRequestBaseManager.dart';

import '../../constant/constant.dart';
import '../../ecycommon/EcyEventBus.dart';
import '../../ecycommon/utils/EcyUserUtil.dart';
import '../../model/EcyApiCommonResponse.dart';
import '../../user/model/EcyUserModel.dart';

class EcyInputCodeLoginPage extends EcyCommonBaseWidget {
  final String mobile;
  // EcyCommonBaseWidget({
  //   required Key key,
  //   required this.title, // 接收一个text参数
  // }) : super(key: key);
  EcyInputCodeLoginPage(this.mobile);

  @override
  _EcyInputCodeLoginPage createState() {
    print(mobile);
    return _EcyInputCodeLoginPage(this, mobile);
  }
}

class _EcyInputCodeLoginPage extends EcyCommonBaseWidgetState {
  String mobile = "";
  bool checked = false;
  int left = 60;
  String code = "";
  bool canNext = false;
  String yysName = "中国电信提供认证服务";
  late EcyCommonBaseWidget controller;
  _EcyInputCodeLoginPage(EcyCommonBaseWidget vc, String _mobile) {
    mobile = _mobile;
    controller = vc;
  }
  @override
  void initState() {
    super.initState();
    requestData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ColorConstant.White,
        appBar: AppBar(
          backgroundColor: ColorConstant.White,
          title: Text(this.title),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(width: MediaQuery.of(context).size.width, height: 140),
            Container(
              margin: const EdgeInsets.only(
                  left: 20, right: 20, top: 0, bottom: 10.0),
              child: Text("输入短信验证码",
                  textAlign: TextAlign.start,
                  style: TextStyle(
                      fontFamily: "PingFag SC",
                      fontWeight: FontWeight.w700,
                      fontSize: 20,
                      color: ColorConstant.CommonColorBlack)),
            ),
            Container(
              margin: const EdgeInsets.only(
                  left: 20, right: 20, top: 0, bottom: 10.0),
              child: Text(
                  "短信验证码发送至 " +
                      (mobile.length > 0
                          ? mobile.substring(0, 3) +
                              " " +
                              mobile.substring(3, 7) +
                              " " +
                              mobile.substring(7, 11)
                          : ""),
                  textAlign: TextAlign.start,
                  style: TextStyle(
                      fontFamily: "PingFag SC",
                      fontWeight: FontWeight.w400,
                      fontSize: 12,
                      color: ColorConstant.CommonColorGray)),
            ),
            Container(
              margin: const EdgeInsets.only(
                  left: 20, right: 15, top: 20, bottom: 10.0),
              child: PinCodeTextField(
                textStyle: TextStyle(
                    color: Colors.black54,
                    fontSize: 18,
                    fontWeight: FontWeight.w400),
                length: 6,
                obscureText: false,
                animationType: AnimationType.fade,
                pinTheme: PinTheme(
                    shape: PinCodeFieldShape.box,
                    selectedBorderWidth: 0,
                    borderWidth: 0,
                    borderRadius: BorderRadius.circular(4),
                    fieldHeight: 52,
                    fieldWidth: 50,
                    activeColor: Colors.grey.shade50,
                    inactiveColor: Colors.grey.shade50,
                    activeFillColor: Colors.grey.shade50,
                    inactiveFillColor: Colors.grey.shade50,
                    disabledColor: Colors.grey.shade50,
                    selectedFillColor: Colors.grey.shade50,
                    selectedColor: Colors.grey.shade50),
                animationDuration: Duration(milliseconds: 300),
                backgroundColor: Colors.white,
                cursorColor: Colors.black,
                enableActiveFill: true,
                onCompleted: (value) {
                  print("Completed");
                  setState(() {
                    code = value;
                    canNext = true;
                  });
                },
                onChanged: (value) {
                  print(value);
                  setState(() {
                    code = value;
                    canNext = value.length == 6 ? true : false;
                  });
                },
                beforeTextPaste: (text) {
                  print("Allowing to paste $text");
                  //if you return true then it will show the paste confirmation dialog. Otherwise if false, then nothing will happen.
                  //but you can show anything you want here, like your pop up saying wrong paste format or etc
                  return true;
                },
                appContext: context,
              ),
            ),
            Container(
                margin: const EdgeInsets.only(
                    left: 20, right: 20, top: 20, bottom: 10.0),
                child: Wrap(
                  children: [
                    Text(left.toString() + "s重新发送",
                        textAlign: TextAlign.start,
                        style: TextStyle(
                            fontFamily: "PingFag SC",
                            fontWeight: FontWeight.w400,
                            fontSize: 12,
                            color: ColorConstant.CommonColorGray)),
                    SizedBox(width: 10, height: 20),
                    Text(
                      "没收到验证码?",
                      textAlign: TextAlign.start,
                      style: TextStyle(
                          fontFamily: "PingFag SC",
                          fontWeight: FontWeight.w400,
                          fontSize: 12,
                          color: Color(0xFF1D6FE9)),
                    )
                  ],
                )),
            GestureDetector(
                onTap: () {
                  if (canNext) {
                    startLogin();
                  }
                },
                child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(26),
                    color: canNext
                        ? ColorConstant.CommonColor
                        : ColorConstant.CommonColorLight,
                  ),
                  margin: const EdgeInsets.only(
                      left: 22, right: 22, top: 24, bottom: 10.0),
                  width: MediaQuery.of(context).size.width - 44,
                  height: 52,
                  alignment: Alignment.center,
                  child: const Text('立即登录',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w700,
                          fontSize: 18,
                          color: ColorConstant.White)),
                ))
          ],
        ));
  }

  void requestData() async {
    controller.showLoading();
    Map<String, dynamic> body = new Map();
    body["tel"] = mobile;
    body["type"] = "1";
    var response = await EcyRequestbasemanager().get("/app/api/app/user/sms", body);
    controller.dismissLoading();
    if (response != null) {
      setState(() {
        //模型自动解析
        var resp = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (resp != null) {
          EasyLoading.showToast(resp.msg ?? "发送成功",
              duration: Duration(seconds: 2));
        }
      });
    }
  }

  void startLogin() async {
    try {
      var pwd = EcyEncrptyUtil.aesEncode(code);
      var response = await EcyRequestbasemanager().post("/app/api/app/user/login",
          {"username": mobile, "type": "0", "password": pwd, "loginType": "1"});
      if (response != null) {
        //模型自动解析
        var resp = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (resp != null) {
          if (resp.code == 0 || resp.code == 200) {
            EcyUserModel user = EcyUserModel.fromJson(response["data"]);
            EcyUserUtil.saveLoginedData(user); //缓存登陆信息
            //发送全局通知
            EcyEventBus().emit(EcyEventConst.kLogined);
          } else {
            EasyLoading.showToast(resp.msg ?? "登录失败",
                duration: const Duration(seconds: 2));
          }
        } else {
          EasyLoading.showToast(resp.msg ?? "登录失败",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast(Constant.NET_ERROR);
    }
  }
}
